package com.example.demo;

import com.example.demo.conf.MyRedisTokenStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}


	@RestController
	static class Demo {

		@GetMapping("/get")
		public Object get() {
			return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		}

		@Autowired(required = false)
		private MyRedisTokenStore tokenStore;

		@GetMapping("/login")
		public Object signout() {
			return "success";
		}

		@PostMapping("v1/logout")
		public Object logout(OAuth2Authentication authentication){
			String token = ((OAuth2AuthenticationDetails)authentication.getDetails()).getTokenValue();
//			OAuth2AccessToken accessToken = tokenService.readAccessToken(token);
//			if(accessToken.getRefreshToken() != null) {
//
//			}
			return revokeToken(token);
		}

		private boolean revokeToken(String tokenValue) {
			OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
			if (accessToken == null) {
				return false;
			}
			if (accessToken.getRefreshToken() != null) {
				tokenStore.removeRefreshToken(accessToken.getRefreshToken());
			}
			tokenStore.removeAccessToken(accessToken);
			return true;
		}

	}
}
